--- 山东晨硕光电直读水表, dtype(4) 9600,EVEN
module(..., package.seeall)

local logtag = "LXSY_adr01"
local read_interval = 5000
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local read_command = '010300000002C40B'  --0x01,0x03,0x00,0x00,0x00,0x02,0xc4,0x0b

function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    if udtu and tonumber(udtu.dtype) == 4 then sys.taskInit(init) end
end
local function process(data)
    if #data > 8 then
        local val, v_hex = {}
        v_hex = data:sub(4, 7):toHex()
        val = tonumber(v_hex, 16) / 100
        usrdata.update({val})
        lcd.LCD_DATA[3] = '累计流量:' .. (val or 'ERROR')
    end
end
function init()
    power.openBoost()
    sys.wait(200)
    -- 测试 累计流量12345.67
    while true do
        -- 读取数据
        sys.publish("UART_SENT_RDY_" .. uid, uid, read_command:fromHex())
        -- 等待串口回复
        log.warn(logtag, "间隔5秒等待串口数据")
        result, data = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, read_interval)
        if result then
            if (data) then
                process(data)
            end
            sys.wait(read_interval)
        else
            lcd.LCD_DATA[3] = string.format("U%dD%d NOREADY",uid,udtu.dtype)
            --process(("0103040012d6874434"):fromHex())
        end
    end
end
